<template>
  <div class="announcement-container">
    <CpNavBar title="学在农林"></CpNavBar>
    <van-search
      v-model="objs.newsTitle"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template slot="action">
        <div @click="onClickButton">搜索</div>
      </template>
    </van-search>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <List v-for="(item, index) in list" :key="index" :item="item"></List>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import List from './components/List.vue'
import { getNewsList } from '@/api/user'

export default {
  components: {
    List
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      objs: {
        pageNum: 1,
        pageSize: 5,
        newsTitle: ''
      }
    }
  },
  methods: {
    async onSearch() {
      this.objs.pageNum = 1
      this.list = []
      this.finished = false
      this.loading = true
      await this.onLoad()
    },
    onClickButton() {
      this.onSearch()
    },
    async onLoad() {
      try {
        const res = await getNewsList(this.objs)
        this.list.push(...res.rows)
        if (this.objs.pageNum >= Math.ceil(res.total / this.objs.pageSize)) {
          this.finished = true
        } else {
          this.objs.pageNum++
        }
      } catch (error) {
        console.error('加载数据失败:', error)
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    onRefresh() {
      this.finished = false
      this.objs.pageNum = 1
      this.list = []
      this.loading = true
      this.onLoad()
    }
  }
}
</script>

<style lang="scss" scoped>
.announcement-container {
  padding-top: 46px;
  padding-bottom: 57px;
  width: 100%;
  height: 100%;
  background: #f7f7f7;
  box-sizing: border-box;
}
</style>